#include <text/Lookup.h>
#include <text/LookupState.h>

#include <system/assert.h>

namespace liba {
namespace text {

void SetDictionary(Dictionary* instance)
{
	if (!g_lookupState)
	{
		LIBA_FAIL("Use creator to initialize text subsystem");
		return;
	}

	LIBA_ASSERT(!g_lookupState->GetDictionary() && "Warning to be sure that we don't set dictionary more than once");

	g_lookupState->SetDictionary(instance);
}

struct LookupKey
{
	LookupKey()
	{ }
	LookupKey(
		const Atom& chapter,
		const Atom& section,
		const Atom& id)
		: chapter(chapter)
		, section(section)
		, id(id)
	{ }

	LookupKey(const LookupKey& rhs)
		: chapter(rhs.chapter)
		, section(rhs.section)
		, id(rhs.id)
	{ }
	const LookupKey& operator=(const LookupKey& rhs)
	{
		if (&rhs == this)
			return *this;

		this->chapter = rhs.chapter;
		this->section = rhs.section;
		this->id = rhs.id;

		return *this;
	}

	Atom chapter;
	Atom section;
	Atom id;
};

LookupKey ParseStringId(const std::string& value)
{
	static Atom defaultAtom("default");

	std::string id = value;
	size_t delimIdx = id.rfind("/");
	if (delimIdx == std::string::npos)
		return LookupKey(defaultAtom, defaultAtom, Atom(id));
		
	std::string section = id.substr(0, delimIdx);
	id.erase(0, delimIdx + 1);

	delimIdx = section.rfind("/");
	if (delimIdx == std::string::npos)
		return LookupKey(defaultAtom, Atom(section), Atom(id));

	std::string chapter = section.substr(0, delimIdx);
	section.erase(0, delimIdx + 1);

	return LookupKey(Atom(chapter), Atom(section), Atom(id));
}

const std::wstring& Lookup(const std::string& id)
{
	static std::wstring notFound(L"--- Not Found ---");
	if (!g_lookupState)
	{
		LIBA_FAIL("Use creator to initialize text subsystem");
		return notFound;
	}

	if (!g_lookupState->GetDictionary())
	{
		LIBA_FAIL("Dictionary isn't set");
		return notFound;
	}
	LookupKey key = ParseStringId(id);

	return g_lookupState->GetDictionary()->GetText(key.chapter, key.section, key.id);
}

} // namespace text
} // namespace liba